import React, { useState } from 'react';
import { NavBar, Button } from 'antd-mobile';
import { useNavigate } from 'react-router-dom';
import './dan.css';

const DanPage: React.FC = () => {
  const nav = useNavigate();
  const [activeTab, setActiveTab] = useState('药品');
  const [selectedItems, setSelectedItems] = useState<{[key: string]: number}>({
    'product1': 1,
    'product2': 1,
    'product3': 0
  });

  // 产品数据
  const products = [
    {
      id: 'product1',
      name: '新冠预防中药 (正常人群) 1剂',
      description: '功效: 主要提高免疫力, 预防新冠疾病',
      price: 10.08,
      image: '/src/assets/1.png',
      tags: ['处方药', '限购5剂'],
      category: '新冠预防中药'
    },
    {
      id: 'product2',
      name: '新冠预防中药 (体弱人群) 1剂',
      description: '功效: 主要提高免疫力, 预防新冠疾病',
      price: 11.80,
      image: '/src/assets/2.png',
      tags: ['处方药', '限购5剂'],
      category: '新冠预防中药'
    },
    {
      id: 'product3',
      name: '新冠预防中药 (儿童人群) 1剂',
      description: '功效: 主要提高免疫力, 预防新冠疾病',
      price: 9.80,
      image: '/src/assets/3.png',
      tags: ['处方药'],
      category: '新冠预防中药'
    }
  ];

  // 分类数据
  const categories = [
    { id: 'covid', name: '新冠预防中药', active: true },
    { id: 'common', name: '普通用药', active: false },
    { id: 'cold', name: '感冒用药 (非处方)', active: false }
  ];

  // 标签页数据
  const tabs = ['药品', '检查', '检验'];

  // 计算总价和选中数量
  const totalAmount = products.reduce((sum, product) => {
    return sum + (product.price * (selectedItems[product.id] || 0));
  }, 0);

  const selectedCount = Object.values(selectedItems).reduce((sum, count) => sum + count, 0);

  // 数量调整
  const adjustQuantity = (productId: string, delta: number) => {
    setSelectedItems(prev => {
      const current = prev[productId] || 0;
      const newValue = Math.max(0, current + delta);
      return { ...prev, [productId]: newValue };
    });
  };

  // 提交订单
  const handleSubmit = () => {
    const orderItems = products.filter(product => selectedItems[product.id] > 0);    
    if (orderItems.length === 0) {
      alert('请选择至少一个商品');
      return;
    }

    console.log('dan页面 - 选中的商品:', orderItems);
    console.log('dan页面 - 计算的总金额:', totalAmount);

    // 创建订单数据
    const orderData = {
      orderNo: `DAN${Date.now()}`,
      items: orderItems.map(item => ({
        ...item,
        quantity: selectedItems[item.id]
      })),
      totalAmount: totalAmount,
      createdAt: new Date().toISOString()
    };

    console.log('dan页面 - 创建的订单数据:', orderData);

    // 保存到本地存储
    localStorage.setItem('danPendingOrder', JSON.stringify(orderData));
    
    // 跳转到支付页面
    nav('/zhi', { state: { from: 'dan', order: orderData } });
  };

  return (
    <div className="dan-page">
      {/* 顶部导航栏 */}
      <NavBar
        onBack={() => nav(-1)}
        style={{
          background: '#fff',
          borderBottom: '1px solid #f0f0f0'
        }}
      >
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%' }}>
          <span style={{ fontSize: '18px', fontWeight: 600, color: '#333' }}>开单申请</span>
         
        </div>
      </NavBar>

      {/* 标签页导航 */}
      <div className="tab-navigation">
        <div className="tab-list">
          {tabs.map(tab => (
            <div
              key={tab}
              className={`tab-item ${activeTab === tab ? 'active' : ''}`}
              onClick={() => setActiveTab(tab)}
            >
              {tab}
            </div>
          ))}
        </div>
        <div className="order-record">
          <span>开单记录 &gt;</span>
        </div>
      </div>

      <div className="main-content">
        {/* 左侧分类栏 */}
        <div className="category-sidebar">
          {categories.map(category => (
            <div
              key={category.id}
              className={`category-item ${category.active ? 'active' : ''}`}
            >
              {category.name}
            </div>
          ))}
        </div>

        {/* 右侧产品列表 */}
        <div className="product-list">
          {products.map(product => (
            <div key={product.id} className="product-card">
              <div className="product-image">
                <img src={product.image} alt={product.name} />
              </div>
              <div className="product-info">
                <div className="product-name">{product.name}</div>
                <div className="product-description">{product.description}</div>
                <div className="product-price">¥{product.price.toFixed(2)}</div>
                <div className="product-tags">
                  {product.tags.map((tag, index) => (
                    <span
                      key={index}
                      className={`tag ${index === 0 ? 'prescription' : 'limit'}`}
                    >
                      {tag}
                    </span>
                  ))}
                </div>
              </div>
              <div className="quantity-control">
                <button
                  className="quantity-btn"
                  onClick={() => adjustQuantity(product.id, -1)}
                  disabled={selectedItems[product.id] <= 0}
                >
                  -
                </button>
                <span className="quantity-value">{selectedItems[product.id] || 0}</span>
                <button
                  className="quantity-btn"
                  onClick={() => adjustQuantity(product.id, 1)}
                >
                  +
                </button>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* 底部汇总栏 */}
      <div className="bottom-summary">
        <div className="summary-info">
          <div className="selected-count">
            <span className="count-icon">📋</span>
            <span>已选{selectedCount}项</span>
          </div>
          <div className="total-amount">合计: ¥{totalAmount.toFixed(2)}</div>
        </div>
        <Button
          color="primary"
          size="large"
          onClick={handleSubmit}
          className="submit-btn"
        >
          提交
        </Button>
      </div>

      {/* 水印 */}
      {/* <div className="watermark">北京八维教育</div> */}
    </div>
  );
};

export default DanPage;